<?php
/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/02/03
 */
namespace api\modules\v1\controllers;

use common\logic\Cabin;
use common\logic\Order;
use common\logic\Tour;
use common\logic\Trip;
use common\tool\Currency;
use Yii;
use yii\validators\Validator;
use yii\web\Controller;
use yii\web\Response;

class OrderController extends Controller {
    public $enableCsrfValidation = false;

    public function beforeAction($action) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return parent::beforeAction($action);
    }

    protected function verbs() {
        return [
            'delete' => ['POST'],
            'cancel' => ['POST'],
        ];
    }

    public function actionList() {
        if (Yii::$app->user->isGuest) {
            return [
                'code' => 403,
                'msg' => '未登录'
            ];
        }
        if ($orderId = Yii::$app->request->get('orderId')) {
            $res = Order::getDetail(Yii::$app->user->id, $orderId);
            if ($res['err'] != 0) {
                return [
                    'code' => 404,
                    'msg' => $res['msg']
                ];
            }
            Order::orderPayTimeout($res['data']);
            $data = [$res['data']];
            $page = 1;
            $total = 1;
        } else {
            $page = Yii::$app->request->get('page', 1);
            $limit = Yii::$app->request->get('page', 20);
            $r = Order::getOrders(Yii::$app->user->id, $page, $limit);
            $total = $r['total'];
            $data = $r['list'];
        }
        $list = [];
        foreach ($data as $k => $v) {
            Order::orderPayTimeout($v);
            $tripData = Trip::getTrip($v['trip_id']);
            $trip = $tripData['list'][0];
            $list[] = [
                "orderId" => $v['order_id'],
                "boatNameCN" => $tripData['boatName'],
                "boatNameEN" => $tripData['boatNameEN'],
                "orderCreateTime" => (int)($v['ctime'] / 1000),
                "departureDate" => $trip['departureDate'],
                "arrivalDate" => $trip['arrivalDate'],
                "theme" => $trip['nameCN'] ?: $trip['nameEN'],
                "count" => count(json_decode($v['contact'], true)),
                "roomType" => "",
                "status" => (int)$v['order_status'],
                "perPrice" => [
                    'unit' => '€',
                    'value' => $v['unitprice'] / 100
                ],
                "price" => [
                    'unit' => '￥',
                    'value' => $v['price'] / 100
                ],
                'imageUrl' => $tripData['boatImage'],
                'payType'=>$v['payment']['type']??'',
            ];
        }

        return [
            'code' => 200,
            'data' => [
                'list' => $list,
                'total' =>$total,
                'page' => $page,
            ]
        ];
    }

    public function actionDetail() {
        if (Yii::$app->user->isGuest) {
            return [
                'code' => 403,
                'msg' => '未登录'
            ];
        }
        $orderId = Yii::$app->request->get('orderId');
        $res = Order::getDetail(Yii::$app->user->id, $orderId);
        if ($res['err'] === 0) {
            $order = $res['data'];
            Order::orderPayTimeout($order);
            $tripData = Trip::getTrip($order['trip_id']);
            $trip = $tripData['list'][0];
            $tour = Tour::getTours([$trip['tourId']])[0]??[];
            $cabin = Cabin::getOneCabin($order['cabin_id']);
            $contactCount = count(json_decode($order['contact'], true));
            return [
                'code' => 200,
                'data' => [
                    "orderId" => $order['order_id'],
                    "boatNameCN" => $tripData['boatName'],
                    "boatNameEN" => $tripData['boatNameEN'],
                    "departureDate" => $trip['departureDate'],
                    "arrivalDate" => $trip['arrivalDate'],
                    "orderCreateTime" => (int)($order['ctime'] / 1000),
                    'serverTime' => time(),
                    'orderPayTimeout' => Yii::$app->params['orderPayTimeout'],
                    "status" => (int)$order['order_status'],
                    "dives" => $tour['dives'],
                    'duration' => $tour['duration'],
                    "nights" => $tour['nights'],
                    "theme" => $trip['nameCN'] ?: $trip['nameEN'],
                    "count" => $contactCount,
                    "roomType" => "豪华",
                    "contact" => json_decode($order['contact'], true),
                    "name" => $order['username'],
                    "email" => $order['email'],
                    "phone" => $order['phone'],
                    "useProtect" => $order['use_protect'],
                    "rental" => [],
                    "payedTime" => (int)($order['ctime'] / 1000),//todo
                    "payType" => $order['payment']['type']??'',
                    "perPrice" => [
                        'unit' => '€',
                        'value' => $order['unitprice'] / 100
                    ],
                    "perPriceCN" => [
                        'unit' => '￥',
                        'value' => $order['unitprice'] * $order['exchange_rate'] / 100,
                    ],
                    "actualPrice" => [
                        'unit' => '€',
                        'value' => $order['unitprice'] / 100 * $contactCount
                    ],
                    //后端实际支付
                    "totalPrice" => [
                        'unit' => '￥',
                        'value' => $order['price'] / 100
                    ],
                    "fund" => $order['fund_amount'],
                    "message" => $order['message'],
                    'imageUrl' => $tripData['boatImage'],

                    "cabinId" => $cabin['id'],
                    "roomName" => $cabin['name_cn'],
                    "bedding" => $cabin['bedding_cn'],
                    "bathRoom" => (bool)$cabin['bathroom'],
                    //"cabinCount" => (int)$cabin['cabin_number'],
                    "deck" => $cabin['deck_cn'],
                    "aircon" => (bool)$cabin['aircon'],
                ],
            ];
        } else {
            return [
                'code' => 404,
                'msg' => $res['msg']
            ];
        }
    }

    public function actionPay() {
        $a = '{"code":200,"data":{"url":""}}';
        return json_decode($a, true);
    }

    public function actionCreate() {

    }

    public function actionCancel() {
        if (Yii::$app->user->isGuest) {
            return [
                'code' => 403,
                'msg' => '未登录'
            ];
        }
        $orderId = Yii::$app->request->post('orderId');
        $res = Order::userCancel(Yii::$app->user->id, $orderId);
        if ($res['err'] === 0) {
            return [
                'code' => 200,
            ];
        } else {
            return [
                'code' => 404,
                'msg' => $res['msg']
            ];
        }
    }

    public function actionDelete() {
        if (Yii::$app->user->isGuest) {
            return [
                'code' => 403,
                'msg' => '未登录'
            ];
        }
        $res = Order::deleteOrder(Yii::$app->request->post('orderId'));
        if ($res['err'] === 0) {
            return [
                'code' => 200,
            ];
        } else {
            return [
                'code' => 404,
                'msg' => $res['msg']
            ];
        }
    }
}
